/*
Irving Derin:
 This is a simple sketch that allows for the transmission of 9 bytes to a recieving 
 coordinator. The recieving address for this coordinator is "0x0010", this is the 
 ATMY value that can be set either using a serial connection directly to the boards 
 that are going to be transmitting. 
 
 
 */

#include <SoftwareSerial.h>  //Serial Library
#include <stdlib.h>
#include <XBee.h>            //Xbee Library
XBee xbee = XBee();  // Creates XBee object 


uint8_t payload[] = { 0, 0 };                   

Tx16Request tx = Tx16Request(0x0010, payload, sizeof(payload)); // Creation of the object to be sent

//TxStatusResponse txSatus = TxStatusResponse();

//int Led = 13;

int CurrentByte = 0;
char inByte = 0;
String Serial_Input = "";
long Output_to_Hex = 0;
boolean ReadSerial = false;

void setup(){

  Serial.begin(9600);
  xbee.begin(9600);
  delay(1500);
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);

}

void loop(){
  while(Serial.available() > 0){
    
    inByte = Serial.read();
    Serial_Input += inByte;
    ReadSerial = true;
  }
  // Serial.println(Serial_Input);
if(ReadSerial == true){
  Serial.println("Data was got");
  
  Modulate(Serial_Input);
  xbee.send(tx);
  Serial_Input = "";
  delay(5000);
  Serial.flush();
  ReadSerial = false;
  
}
}



void Modulate(String x){

  char From_Serial_String[x.length()+1];
  x.toCharArray(From_Serial_String, sizeof(From_Serial_String));
  Output_to_Hex = atol(From_Serial_String);
  //Serial.println(Output_to_Hex);  
  //Serial.println(x);
  long Hinput;
  Hinput = Output_to_Hex;
  payload[0] = Hinput >> 16 & 0xff;
  payload[1] = (Hinput >> 8 & 0xff);
  payload[2] = (Hinput & 0xff);

  //Serial.println(payload[0]);
  //Serial.println(payload[1]);
  //Serial.println(payload[2]);
}

/*
        Demodulation:
 unsigned long n = 0;
 n = c | (b << 8) | (a << 16);
 cout << "First byte is " << a << ", the next byte is " << b << ",Finally : " << c << endl;
 cout << "Combined, n is equal too: " << n << endl;
 float blah = (float)n;
 cout << "when n is multiplied by 10 raised to the " << d << " power, you get " << blah * pow (10,d) << endl;
 
 
 */








